package dormouse.vfs.ui.renderers;

import java.awt.BorderLayout;
import java.awt.Component;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.pdfbox.pdfviewer.PDFPagePanel;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PagePanel;

/**
 * This renderer renders PDF files.
 */
public class PDFRenderer extends PDFPagePanel implements IFileRenderer {

    private static final String[] EXTS = {"pdf"};
    /**
     * 
     */
    private static final long serialVersionUID = -6256207627759241014L;

    public PDFRenderer() throws IOException {
        super();
    }

    public void render(FileObject file) {
        PagePanel panel = new PagePanel();


        ReadableByteChannel channel = null;


        ByteBuffer buf = ByteBuffer.allocateDirect(200000);
        try {
            long size = file.getContent().getSize();
            channel = Channels.newChannel(file.getContent().getInputStream());
            channel.read(buf);
            PDFFile pdffile = new PDFFile(buf);

            // show the first page
            PDFPage page = pdffile.getPage(0);

            this.setLayout(new BorderLayout());
            this.add(panel);
            panel.showPage(page);
           
        } catch (FileSystemException ex) {
            Logger.getLogger(PDFRenderer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex){
             Logger.getLogger(PDFRenderer.class.getName()).log(Level.SEVERE, null, ex);
        } finally{
            try {
                channel.close();
            } catch (IOException ex) {
                Logger.getLogger(PDFRenderer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }






    }

    public String[] getFileExtensions() {
        return EXTS;
    }

    public Component getComponent() {
        return this;
    }
}
